package com.itheima.file;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.core.codec.EncodingException;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExcelUtil {

    private final static String excel2003L = ".xls";    //2003- 版本的excel
    private final static String excel2007U = ".xlsx";   //2007+ 版本的excel
    //获取标题
    private final String[] titles = {"日期", "可预约数量"};

    /**
     * 描述：获取IO流中的数据，组装成List<List<Object>>对象
     *
     * @param in,fileName
     * @return
     * @throws Exception
     */
    public List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception {
        List<List<Object>> list = null;

        //创建Excel工作薄  
        Workbook work = this.getWorkbook(in, fileName);
        if (null == work) {
            throw new Exception("创建Excel工作薄为空！");
        }
        Sheet sheet = null;  //页数
        Row row = null;  //行数
        Cell cell = null;  //列数

        list = new ArrayList<List<Object>>();
        //遍历Excel中所有的sheet  
        // 将最大的列数记录下来
        int lastCellNum = 0;
        for (int i = 0; i < work.getNumberOfSheets(); i++) {
            sheet = work.getSheetAt(i);
            if (sheet == null) {
                continue;
            }

            //遍历当前sheet中的所有行  
            for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
                row = sheet.getRow(j);
                if (row == null || row.getFirstCellNum() == j) {
                    continue;
                }

                //遍历所有的列  
                List<Object> li = new ArrayList<Object>();
                // 比较当前行的列数跟表的最大的列数
                if (j == sheet.getFirstRowNum()) {
                    // 将第一行的列数设为最大
                    lastCellNum = row.getLastCellNum();
                } else {
                    lastCellNum = lastCellNum > row.getLastCellNum() ? lastCellNum : row.getLastCellNum();
                }
                for (int y = row.getFirstCellNum(); y < lastCellNum; y++) {
                    cell = row.getCell(y);
                    li.add(this.getValue(cell));
                }
                list.add(li);
            }
        }

        return list;

    }

    /**
     * 描述：根据文件后缀，自适应上传文件的版本
     *
     * @param inStr,fileName
     * @return
     * @throws Exception
     */
    public Workbook getWorkbook(InputStream inStr, String fileName) throws Exception {
        Workbook wb = null;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (excel2003L.equals(fileType)) {
            wb = new HSSFWorkbook(inStr);  //2003-
        } else if (excel2007U.equals(fileType)) {
            wb = new XSSFWorkbook(inStr);  //2007+
        } else {
            throw new Exception("解析的文件格式有误！");
        }
        return wb;
    }

    /**
     * 描述：对表格中数值进行格式化
     *
     * @param cell
     * @return
     */
    //解决excel类型问题，获得数值
    public String getValue(Cell cell) {
        String value = "";
        if (null == cell) {
            return value;
        }
        switch (cell.getCellType()) {
            //数值型
            case NUMERIC:
                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                    //如果是date类型则 ，获取该cell的date值
                    Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
                    // 根据自己的实际情况，excel表中的时间格式是yyyy-MM-dd HH:mm:ss还是yyyy-MM-dd，或者其他类型
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    // 由于方法的返回值类型为String，这里将Date类型转为String，便于统一返回数据
                    value = format.format(date);
                    ;
                } else {// 纯数字
                    BigDecimal big = new BigDecimal(cell.getNumericCellValue());
                    value = big.toString();
                    //解决1234.0  去掉后面的.0
                    if (null != value && !"".equals(value.trim())) {
                        String[] item = value.split("[.]");
                        if (1 < item.length && "0".equals(item[1])) {
                            value = item[0];
                        }
                    }
                }
                break;
            //字符串类型   
            case STRING:
                value = cell.getStringCellValue().toString();
                break;
            // 公式类型
            case FORMULA:
                //读公式计算值
                value = String.valueOf(cell.getNumericCellValue());
                if (value.equals("NaN")) {// 如果获取的数据值为非法值,则转换为获取字符串
                    value = cell.getStringCellValue().toString();
                }
                break;
            // 布尔类型
            case BOOLEAN:
                value = " " + cell.getBooleanCellValue();
                break;
            default:
                value = cell.getStringCellValue().toString();
        }
        if ("null".endsWith(value.trim())) {
            value = "";
        }
        return value;
    }


    public void export(List<String> dates, HttpServletResponse response) throws Exception {
        XSSFWorkbook workbook = new XSSFWorkbook();

        XSSFSheet sheet = workbook.createSheet("预约设置模板");
        sheet.setDefaultColumnWidth(20);
        //  getColumnStyle(workbook, false, true, HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
        //创建第一行
        XSSFRow titleRow = sheet.createRow(0);
        //创建样式
        XSSFCellStyle titleStyle = this.getColumnStyle(workbook, true, true, HorizontalAlignment.CENTER, VerticalAlignment.CENTER,IndexedColors.GREY_25_PERCENT.getIndex());
        //写入标题
        for (int i = 0; i < titles.length; i++) {
            XSSFCell cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(titleStyle);
        }
        //填充数据
        XSSFCellStyle contentStyle = workbook.createCellStyle();
        contentStyle.setAlignment(HorizontalAlignment.CENTER);
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        for (int i = 0; i < dates.size(); i++) {
            XSSFRow row = sheet.createRow(i + 1);
            XSSFCell cell = row.createCell(0);
            cell.setCellValue(dates.get(i));
            cell.setCellStyle(contentStyle);
            /*
            for (int j = 0; j < titles.length; j++) {
                HSSFCell cell = null;
                switch (j) {
                    case 0:
                        cell = row.createCell(j);
                        cell.setCellValue(i);
                        break;
                    case 1:
                        cell = row.createCell(j);
                        cell.setCellValue(student.getName());
                        break;
                }
            }*/
        }
            String fileName = "预约设置模板";
            String codeFileName = new String((fileName + ".xlsx").getBytes("UTF-8"), "ISO-8859-1");
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + codeFileName);
            try {
                OutputStream out = response.getOutputStream();
                workbook.write(response.getOutputStream());
                out.flush();
                out.close();
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("io异常!");
            }

    }

    /**
     * 单元格样式
     *
     * @param workbook
     * @param fontBold            是否加粗
     * @param isBorder            是否带边框
     * @param horizontalAlignment 水平对齐格式
     * @param verticalAlignment   垂直对齐格式
     * @return
     */
    private XSSFCellStyle getColumnStyle(XSSFWorkbook workbook,
                                         boolean fontBold,
                                         boolean isBorder,
                                         HorizontalAlignment horizontalAlignment,
                                         VerticalAlignment verticalAlignment,
                                         short colorCode
                                         ) {
        // 设置字体
        XSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short) 12);
        //设置字体名字
        font.setFontName("宋体");
        font.setBold(fontBold);
        //设置样式;
        XSSFCellStyle style = workbook.createCellStyle();
        // 是设置前景色不是背景色
        style.setFillForegroundColor(colorCode);
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        if (isBorder) {
            //设置底边框;
            style.setBorderBottom(BorderStyle.THIN);
            //设置底边框颜色;
            style.setBottomBorderColor(IndexedColors.BLACK.index);
            //设置左边框;
            style.setBorderLeft(BorderStyle.THIN);
            //设置左边框颜色;
            style.setLeftBorderColor(IndexedColors.BLACK.index);
            //设置右边框;
            style.setBorderRight(BorderStyle.THIN);
            //设置右边框颜色;
            style.setRightBorderColor(IndexedColors.BLACK.index);
            //设置顶边框;
            style.setBorderTop(BorderStyle.THIN);
            //设置顶边框颜色;
            style.setTopBorderColor(IndexedColors.BLACK.index);
        }
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(horizontalAlignment);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(verticalAlignment);
        return style;
    }
}